﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace FishServe.Build.Common
{
	public static class MyExtensions
	{
		public static string GetFileHash(this FileInfo fileInfo, string hashAlgorithmName)
		{
			return fileInfo.GetFileHash(GetHashAlgorithm(hashAlgorithmName));
		}
		public static string GetFileHash(this FileInfo fileInfo, HashAlgorithm hashAlgorithm)
		{
			return GetFileHash(fileInfo.FullName, hashAlgorithm);
		}

		public static string GetFileHash(string fullFilePath, HashAlgorithm hashAlgorithm)
		{	
			byte[] hashBytes = null;
			try
			{
				hashBytes = hashAlgorithm.ComputeHash(File.ReadAllBytes(fullFilePath));
			}
			catch (Exception)
			{
				Console.WriteLine(String.Format("Failed to compute hash for file '{0}'.", fullFilePath));
				throw;
			}
			return Convert.ToBase64String(hashBytes);
			//return BitConverter.ToString(hashBytes);
		}
		public static string GetFileHash(string fullFilePath, string hashAlgorithmName)
		{
			return GetFileHash(fullFilePath, GetHashAlgorithm(hashAlgorithmName));
		}

		private static HashAlgorithm GetHashAlgorithm(string hashAlgorithmName)
		{
			HashAlgorithm algorithm = null;

			switch (hashAlgorithmName.ToUpper())
			{
				case "SHA1":
					algorithm = new SHA1Managed();
					break;
				case "SHA256":
					algorithm = new SHA256Managed();
					break;
				case "SHA384":
					algorithm = new SHA384Managed();
					break;
				case "SHA512":
					algorithm = new SHA512Managed();
					break;
				case "MD5":
					algorithm = new MD5CryptoServiceProvider();
					break;
				default:
					Console.WriteLine(String.Format("Unrecognised hash algorithm '{0}'", hashAlgorithmName));
					throw new Exception(String.Format("Unrecognised hash algorithm '{0}'", hashAlgorithmName));
			}
			return algorithm;

		}
	}
}
